<template>
  <div class="login">
    <div class="box">
      <h2>管理平台</h2>
      <el-form
          size="small"
          ref="formRef"
          :model="formData"
          status-icon
          :rules="rules"
          label-width="40px">

        <el-form-item label="账号" prop="loginId">
          <el-input v-model.number="formData.loginId"/>
        </el-form-item>
        <el-form-item label="密码" prop="loginPassword">
          <el-input v-model="formData.loginPassword" type="password"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(formRef)">登录</el-button>
          <el-button @click="resetForm(formRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue'
import {ElNotification, FormInstance, FormRules} from 'element-plus'
import {$login} from "../api/admin.ts";
import {useRouter} from "vue-router";
import UseUser from '../store/user.ts'

let router = useRouter();
const globalUser = UseUser()
const formRef = ref<FormInstance>()
const formData = reactive({
  loginId: '',
  loginPassword: '',
})
const rules = reactive<FormRules<typeof formData>>({
  loginId: [{
    validator: (_: any, value: any, callback: any) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }, trigger: 'blur'
  }],
  loginPassword: [{
    validator: (_: any, value: any, callback: any) => {
      if (value === '') {
        callback(new Error('请输入账号'))
      } else {
        callback()
      }
    }, trigger: 'blur'
  }],
})
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        await $login(formData)
        ElNotification({title: "温馨提示", message: "登录成功", type: "success"})
      } catch (e) {
        ElNotification({title: "温馨提示", message: `登录出错 ${e}`, type: "error"})
        // 假如登录成功
        globalUser.setUser({userId: "1"})
        router.push('/index')
      }
    } else {
      ElNotification({title: "温馨提示", message: "登录出错", type: "error"})
      return false
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped lang="scss">
.login {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(to bottom, #142334, #98b9df);
  display: flex;
  justify-content: center;
  align-items: center;

  .box {
    width: 400px;
    padding: 20px;
    border: 1px solid white;

    :deep(.el-form-item__label) {
      color: white;
    }


    h2 {
      color: white;
      font-size: 20px;
      text-align: center;
      margin-bottom: 20px;
    }
  }
}
</style>